package org.payeco.risk.rules;

import java.lang.reflect.Field;

import org.jeasy.rules.core.CompositeRule;
import org.payeco.risk.annotation.PutRiskRule;
import org.payeco.risk.common.PayecoRiskOpRuleType;
import org.payeco.risk.entity.PayecoRiskRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Strings;

/**
 * @author yps
 * 这是数据的规则表数据转换成一个个组合因子规则
 */
public class PayecoRiskComRule extends CompositeRule {
	
    private static final Logger LOGGER = LoggerFactory.getLogger(PayecoRiskComRule.class);

	private PayecoRiskRule riskRule;
	
	
	public PayecoRiskComRule(PayecoRiskRule riskRule) {
		this.riskRule = riskRule;
		initRules(riskRule);
	}

	private void initRules(PayecoRiskRule riskRule) {
		// 遍历参数
		Field[] fields = riskRule.getClass().getFields();
		for (Field field : fields) {
			// 根据参数找到对应的rule因子
			// TODO 可以在以后添加排序字段的操作
			String value = null;
			try {
				value = field.get(riskRule) + "";
				if (!Strings.isNullOrEmpty(value)
						&& !"UNDEFINED".equalsIgnoreCase(value)) {
					Object rule = PayecoRiskOpRuleType.handler(field.getName().toUpperCase(), riskRule);
					if (rule != null) {
						addRule(rule);
					}
				}
			} catch (IllegalArgumentException e) {
				LOGGER.error(e.getMessage());
			} catch (IllegalAccessException e) {
				LOGGER.error(e.getMessage());
			} catch (Exception e) {
				LOGGER.error(e.getMessage());
			}
		}
	}

	@Override
	public int getPriority() {
		return riskRule.getPriority();
	}

	public PayecoRiskRule getRiskRule() {
		return riskRule;
	}
	
	public void setRiskRule(PayecoRiskRule riskRule) {
		this.riskRule = riskRule;
	}
	
	
}
